package com.vitabuybuy.tv.ui.shopcenter

import android.os.Bundle
import com.blankj.utilcode.util.ScreenUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout
import com.google.gson.reflect.TypeToken
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.library.common.ext.mmkv
import com.library.common.util.JsonUtil

import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.FragmentShopCenterBinding
import com.vitabuybuy.tv.dialog.GoodsScreenPopup
import com.vitabuybuy.tv.dto.*
import com.vitabuybuy.tv.ui.shopcenter.viewmodel.ShopCenterViewModel
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.ui.tencent.chat.MessageListActivity
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import kotlinx.android.synthetic.main.fragment_shop_center.*
import java.util.*

/**
 * 作者：SimGa
 * 日期：2020/11/29
 * 时间：10:49
 * 包名：com.vitabuybuy.tv.ui.cart
 */
class ShopCenterFragment : BaseFragment<ShopCenterViewModel, FragmentShopCenterBinding>() {
    override val layoutId: Int
        get() = R.layout.fragment_shop_center

    private var pageNumber = 1
    private var sort = "featured"
    private var categoryId = -1
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var salePriceDto = SalePriceDto()
    private var areaDialog: BottomDialog? = null
    private var screenPopup: GoodsScreenPopup? = null

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.viewModel = viewModel
        mTabEntities.add(TabEntity(getString(R.string.recommend), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.new_product), 0, 0))
        mTabEntities.add(
            TabEntity(
                getString(R.string.price),
                R.drawable.icon_common_updown,
                R.drawable.icon_common_updown
            )
        )
        mTabLayout_1.setTabData(mTabEntities)
    }

    override fun lazyLoadData() {
        viewModel.getAllBrand()
        val categoryList = JsonUtil.fromJson(
            mmkv.decodeString(MMKVContancts.CATEGORY_LIST, ""),
            object : TypeToken<ArrayList<FirstCategoryDto>>() {}.type
        ) as ArrayList<FirstCategoryDto>
        tlClassification.apply {
            removeAllTabs()
            addTab(
                tlClassification.newTab().setText(getString(R.string.recommend))
                    .setTag(categoryId)
            )
            for (str in categoryList) {
                addTab(tlClassification.newTab().setText(str.name).setTag(str.id))
            }
        }
    }

    override fun eventHandling() {
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getGoodsList(categoryId, sort, pageNumber)
            }
            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber = 1
                viewModel.getGoodsList(categoryId, sort, pageNumber)
            }
        })
        tlClassification.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                categoryId = tab?.tag as Int
                pageNumber = 1
                viewModel.getGoodsList(categoryId, sort, pageNumber)
            }

            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }
        })
        mTabLayout_1.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> {
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown,
                                R.drawable.icon_common_updown
                            )
                        sort = "featured"
                    }
                    1 -> {
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown,
                                R.drawable.icon_common_updown
                            )
                        sort = "new"
                    }
                    2 -> {//点击了价格,价格从高到低
                        sort = "down_price"
                        mTabEntities[2] = TabEntity(
                            getString(R.string.price),
                            R.drawable.icon_common_updown_down,
                            R.drawable.icon_common_updown
                        )
                    }
                }
                pageNumber = 1
                viewModel.getGoodsList(categoryId, sort, pageNumber)
                mTabLayout_1.setTabData(mTabEntities)
            }

            override fun onTabReselect(position: Int) {
                if (position == 2) {//一直点击价格
                    if (sort == "up_price") {//价格从高到低
                        sort = "down_price"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown_down,
                                R.drawable.icon_common_updown
                            )
                    } else if (sort == "down_price") {//从低到高是
                        sort = "up_price"
                        mTabEntities[2] =
                            TabEntity(
                                getString(R.string.price),
                                R.drawable.icon_common_updown_up,
                                R.drawable.icon_common_updown
                            )
                    }
                    pageNumber = 1
                    viewModel.getGoodsList(categoryId, sort, pageNumber)
                }
                mTabLayout_1.setTabData(mTabEntities)
            }
        })
        ivScreen.setOnClickListener {
            screenPopup = GoodsScreenPopup(
                mContext,
                viewModel.brandList.value,
                salePriceDto
            ).apply {
                setAdjustInputMethod(false)
                height = ScreenUtils.getScreenHeight()
                showPopupWindow()
            }
            screenPopup?.onConfirm = { bradList, salePrice, regionId ->
                viewModel.brandList.value = bradList
                salePriceDto = salePrice
                val brandList2 = mutableListOf<BrandDto>()
                viewModel.brandList.value?.run {
                    for (brand in this) {
                        if (brand.isChoose) {
                            brandList2.add(BrandDto(brand.id))
                        }
                    }
                    pageNumber = 1
                    sort = "featured"
                    if (brandList2.size == 0 && salePriceDto.start == 0.00 && salePriceDto.end == 0.00
                        && regionId == -1
                    ) {//就是没有筛选，则重新按正常搜索
                        viewModel.getGoodsList(categoryId, sort, pageNumber)
                    } else {//否则的话，就证明有条件进行搜索
                        viewModel.getScreenGoods(
                            brandList2,
                            salePriceDto,
                            sort,
                            categoryId,
                            pageNumber,
                            regionId
                        )
                    }
                }
            }
            screenPopup?.changeLocation = {
                //这里一定要重新创建
                areaDialog = BottomDialog(mContext, 5)
                viewModel.getRegionList(null)
            }
        }
        ivClassification.setOnClickListener {
            CommodityClassificationActivity.openActivity(
                mContext,
                CommodityClassificationActivity.FROM_GOODS_CENTER
            )
        }
        rlSearch.setOnClickListener { SearchGoodsOrStoreActivity.openActivity(mContext) }
        ivMessage.setOnClickListener {  MessageListActivity.openActivity(mContext)}

    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                refresh.onLoad(msg.arg1)
            }
            2 -> {
                GoodsDetailsActivity.openActivity(mContext, (msg.obj as GoodsDto).id)
            }
            3 -> {
                areaDialog?.let {
                    it.setDataRegion(msg.obj as MutableList<RegionDto>)
                    it.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                if (this.size == 1) {//表明只有国家可选
                                    screenPopup?.setRegion(this[0].id, this[0].name)
                                } else {//表明有国家和下属地区
                                    var area = ""
                                    var regionId = -1
                                    for (selectAble in this) {
                                        regionId = selectAble.id
                                        area = selectAble.name
                                    }
                                    screenPopup?.setRegion(regionId, area)
                                    areaDialog = null
                                }
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (it.isShowing) return
                    it.show()
                }
            }
        }
    }
}